Data Visualisation through interactive dashboards from Dash by Plotly

Data Visualisation
Data Science
Author

Ujas Shah
Dhrumil Bhutaiya
Dhanraj Visapara

Published

February 23, 2025


Alt Text

Img source : https://tinyurl.com/52tk9dnn


Dash is one of the most trusted and widely used framework for building machine learning and data science web apps by Plotly.

     Plotly’s Python graphing library makes interactive, publication-quality graphs. Plotly Dash is considered a python library, which is specificaly designed to build the web based data visualization application using python language. Python has taken over the world, and Dash enterprise is the leading vehicle for delivering Python analytics to business users. With help of Dash Open Source, you can create data apps on your laptop in pure Python, without requiring any Javascript coding, and can also share them to others for data collaboration.

Introduction

     How can we effectively track and visualize the spread of COVID-19 in real-time, providing users with up-to-date and interactive dashboards? How can we analyze and visualize stock market trends to make informed investment decisions? How can we present complex climate change data in an accessible and engaging way to raise awareness and drive action?…..Matplotlib might be an answer, but its applications are limited and static with nearly no level of interactivity. We need something more advanced and easy to use. This is where Plotly from dash comes in…

     Dash from Plotly is a web application development framework built on top of frameworks and libraries like Flask, Plotly.js, and React.js, which is to be coded in Python, eliminating the requirement for any Javascript coding. It creates dynamic dashboards (a visual user interface that presents key information and metrics, i.e. the KPIs (Key Performance Indicators) in an organised manner) using pure Python. However, the syntax while writing the code somewhat represents the code as if it were written in HTML or JS; it is just that it is made simpler.

     The primary purpose of Dash from Plotly is to quickly implement a web interface and create dashboards with Plotly without having to learn javascript, HTML, and other web technologies, making them easy and quick for users. It is a high-level framework used to create beautiful analytical and interactive web-based visualisations, with minimal boilerplate code, that can be displayed in Jupyter notebooks using Dash by plotly. It is widely used due to its cross-platform compatibility, ie, dash apps are rendered in the browser, making them accessible to anyone on any device.

     Apart from this, it is mainly used by data scientists, developers, and businesses to analyse data quickly by building an interactive dashboard where they can easily create custom, visually appealing charts and graphs with high interactivity. It provides a way to combine different representations or views of extensive data and visualise it according to the requirements due to its interactive buildup.

Note: Important links to tutorials and practice sites are given in the navigation bar above. Do check them out as you go through the blog

Installation and Setup

     To install dash in python you have to enter the following command in your Jupyter or Colab notebook. (Can also be ran on Command prompt if you want use Dash through Python IDEs.) These are not all what dash has to offer, but a great set to start with.

# Installing the Dash framework
!pip install -q dash
# Installing dash_html_components which provides a set of HTML components for creating dash layouts
!pip install -q dash_html_components
# Installing dash_core_components, which includes core components like dropdowns, sliders, etc, for interactive elements in Dash
!pip install -q dash_core_components
# Installing dash_bootstrap_components, which includes advanced HTML components and can be used to make tables
!pip install -q dash_bootstrap_components
# Note: The -q flag is to suppress the output of a !pip command, and it's entirely optional.

To start working with Dash, import the following libraries into your work environment:

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash import callback, Dash

import pandas as pd   #for data manipulation
import plotly.express as px   #for data visualisation.....it gives better visualisation options
#alternatively matplotlib can also be used.

     If you wish to use Dash without having to install all the libraries and dependencies, you can use wasmdash.vercel whose link is given in the navbar, where you can online simulate your app without needing to install these. But remember if you want to make a proper app for some purpose, it is always advised to do using python IDEs.

Code Structure

     The structure of a dash app code is divided into mainly two parts, the Layout and the Callback. The layout defines how the app will look, what all components and features would be included, etc. Anything that can be seen on the app is layout. The callback part is what makes dash apps interactive. It includes taking inputs, producing respective outputs and all the processing and functions required in between. The below code summarises what a basic dash code looks like.

app = dash.Dash()   #defining a dashboard
app.layout = html.Div([
    ## layout ##
])
@callback(
    ## callback inputs and outputs ##
)
## callback functions ##

if __name__ == '__main__':
    app.run(debug=True)

Layout

     Layout is the structure of the web app we are developing. It shows which and where the elements like graphs, text button, input and output will be shown. Dash is a web app framework that provides pure Python abstraction around HTML, CSS, and JavaScript. Instead of writing in HTML, you can compose your layout using Python with the Dash HTML Components module (dash.html), and the components of the app would be defined by the dash-core-components. Lets take a deeper look upon this:

DASH-HTML-COMPONENTS

     These are used in a very similar way you use html, the codes and syntax is nearly the same, except you use html. instead of <> to define your tags. Thus we won’t discuss more upon it here and keep our focus on the new dash functions and objects we are going to learn.

DASH-CORE-COMPONENTS

     Lets see some of the different dash features which we create use using dash-core-components, includeing basic features like dropdown, sliders, checklists and interactive graphs. The Dash Core Components module (dash.dcc) gives you access to many interactive components, including dropdowns, checklists, and sliders. This all may be done for reading some large data sets, or building app layouts, and to produce components for giving back the output using callback (Callbacks are defined functionality within an app that are triggered by user interaction. More on it further down.)

VISUAL LAYOUTS

     Visual layouts are the in built dash features used to make the app more interactive and visually appealing. This visual layouts contains features and components like:

  1. Dropdown
dcc.Dropdown(["Gujarat", "Maharashtra", "Rajasthan", "Delhi", "West Bengal", "Karnataka"], "Gujarat") #Defines the layout of the app using a Div container to hold UI components.

This is an example of a dropdown with some states as options and the default value as Gujarat.

  1. Slider
dcc.Slider(-5, 10, 1, value=-3)

In the slider we can also can also specify the range of values instead of a single value and such sliders are known as range sliders

  1. Checkboxes
dcc.Checklist(["Gujarat", "Maharashtra", "Rajasthan", "Delhi", "West Bengal", "Karnataka"],      # makes the checklist of the items in the list, they may be shown in line using inline(True)
                  ["Gujarat","Delhi"]) ## Gujarat and Delhi will be chosen by default
  1. Buttons

     The below code not only shows the use of button as a dcc feature, but also gives a idea of a dash code and a very naive glimpse of some other functionalities possible thorough dash, some of which are discussed later in the blog.

from dash import Input, Output, State # imports important components which are useful in building the web app, handling callbacks and managing the user interaction

# importing the external style sheet which helps in styling the app
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app4 = Dash(__name__, external_stylesheets=external_stylesheets)  # initializes
app4.layout = html.Div([
    html.Div(dcc.Input(id='input-box', type='text')),  # Creates a text input field where users can enter values
    html.Button('Submit', id='button-example-1'),   # creates the button named submit to trigger the action
    html.Div(id='output-container-button',                   #Creates a div to display output messages.
             children='Enter a value and press submit')
])

# defining the callback function which updates the value of the output
@callback(
    Output('output-container-button', 'children'),   # Specifies that the callback updates the text inside the output div
    Input('button-example-1', 'n_clicks'),  # trigger
    State('input-box', 'value')) # takes the input value when triggered

# defining the function to update the output message based on the input
def update_output(n_clicks, value):
    return 'The assignment was of "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    )

if __name__ == '__main__':
    app4.run(debug=True, port = 4999)

Output

Alt Text
Alt Text


     Apart from this, there are many other visual components feature which can be used in dash. The offcial dash tutorial can be referred to learn more about them.

     All the components here should also have a parameter called id, which will be referred to as component_id in the callback, if more than once a same type of component is used and referred in the callback. You can define the id = ‘any string’ for each of these dcc components. An example is shown below. These work as identities for each layout component so you can later refer to them in the callback decorator and callback functions.

dcc.Slider(-5, 10, 1, value=-3, id = 'slider1')
OUTPUT COMPONENTS

Output components display results dynamically in Dash apps. It may contain the graphs, images, tables in it.

Tables
import dash.dash_table as dt

df = pd.DataFrame({
    "Name": ['Dhrumil','Ujas','Dhanraj','Devarsh','Rishabh'],
    "Marks": [35,37,33,40,38]
})

app1 = dash.Dash()
app1.layout = html.Div([
    dt.DataTable(id="output-table", data=df.to_dict("records"), columns=[{"name": i, "id": i} for i in df.columns], style_cell={'textAlign': 'center'})
])

# Here 'id' assigns an ID to the table which could be later be helpful in the callback. It is also used to distinguish between multiple components as discussed before

if __name__ == '__main__':
    app1.run(debug=True, port = 5000)
Output
Alt Text


Graphs
app2 = dash.Dash(__name__)

# Load the iris dataset

df = px.data.iris()

# Create a scatter plot

fig = px.scatter(df, x="sepal_width", y="sepal_length") #matplotlib can also be used here

# Define the app layout

app2.layout = html.Div([
    html.H1("Iris Scatter Plot"), #equivalent to <h1></h1>
    dcc.Graph(figure=fig)
])

# Run the Dash app

if __name__ == '__main__':
    app2.run_server(debug=True, port = 5001)
Output
Alt Text


     Remember to use different ports if you are working on two or more dash codes simultaneously, else they could overlap and affect each others outputs, ie, they will show the same app. Understand it in the way that each port can have one dash app code running.

     These are some basic features of the dash-core-components which can be used to make the app more interactive. These are very basic features and are used very frequently while doing dash on a larger scale. Nonetheless, there are many other key features which are very helpful in making the app more interactive and human friendly. Do refer the official tutorial for more.

TABLE LAYOUTS (using dbc)
import dash_bootstrap_components as dbc

# Initialize the app with Bootstrap

app5 = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

# Layout with styled rows and columns

app5.layout = dbc.Container([
    dbc.Row([
        dbc.Col(html.Div("Column 1 - Row 1", className="p-3 border text-center"), width=4),
        dbc.Col(html.Div("Column 2 - Row 1", className="p-3 border text-center"), width=4),
        dbc.Col(html.Div("Column 3 - Row 1", className="p-3 border text-center"), width=4)
    ], className="mb-3 bg-warning"),  # Yellow row
    dbc.Row([
        dbc.Col(html.Div("Column 1 - Row 2", className="p-3 border text-center"), width=6),
        dbc.Col(html.Div("Column 2 - Row 2", className="p-3 border text-center"), width=6)
    ], className="mb-3 bg-warningy"),  # Yellow row
    dbc.Row([
        dbc.Col(html.Div("Full-width Column in Row 3", className="p-3 border text-center"), width=12)
    ], className="bg-warning")  # Blue row
], fluid=True, style={"background-color": " #00FF00"})  # Green background for columns

# Run the app
if __name__ == "__main__":
    app5.run_server(debug=True, port = 5002)
Output
Alt Text


     You can also stylize the divisions and subdivisions created by html.div using codes as follows, which are similar to how we style div tags in html. You have to just place code pieces like this (include and exclude parameters you want and don’t) before the end of html.div.

style={'width': '49%', 'display': 'inline-block', 'padding': '0 20'})

     Don’t forget do refer the official tutorial and continue learning about new components in layouts….there are a plenty.

Callback

     Callback is the interactivity in the dash app. It connects the components from the layout part of the code to the output making it interactive for the user. Callback is made of 2 different sections: callback decorator and callback function.

Callback Decorator:

     It is the part of callback that defines Input and Output for the ineteractivity required. It will always have minimum 2 arguments, which are input and output. It can of course have multiple inputs and multiple outputs, but it will have always have minimum one input and one output argument in it. These input and output components contain the component id(which tells which component to listen too, ie, which component to take input from and which to use for giving outputs) and component property(which property or parameter of the component to listen to). The components used here are the same as those created in the layout section. Any component you want to use here must be first created in the layout.

Callback Function:

     Every input and output inside the callback decorator has to be represented in the callback function. Ellaborating, there can be as many functions that you want in the callback function section, each taking the defined inputs and outputs in order, but should cover all the inputs and outputs defined. There are two things to note and remeber here, one, all inputs and outputs are to be used as parameters and return respectively, and second, they are to be used in order, which also means that you cannot use any input or output more than once. Each output must be unique to a single callback to avoid conflicts and ensure proper updates. The inputs would go into the parameters according to their order and the return values would be assigned to outputs in order.

Output(component_id = {}, component_property = {})
Input(component_id = {}, component_property = {})

While defining the Outputs and the Inputs, we can define them by using component_id = {the id for that defined in layout}, to use the same type of component multiple times. The below code does not explicitly use this as there is only one component (Input).

Let us practically see the application of callback in a dash code.

app = dash.Dash()
# layout
app.layout = html.Div([
    dcc.Input(            # Here we create the input field with ID 'num-multi' which has its default value has 5
        id='num-multi',
        type='number',
        value=5
    ),
    html.Table([                                                         # html.Tr makes the changes in the row
        html.Tr([html.Td(['x', html.Sup(2)]), html.Td(id='square')]),
        html.Tr([html.Td(['x', html.Sup(3)]), html.Td(id='cube')]),
        html.Tr([html.Td([2, html.Sup('x')]), html.Td(id='twos')]),
        html.Tr([html.Td([3, html.Sup('x')]), html.Td(id='threes')]),
        html.Tr([html.Td(['x', html.Sup('x')]), html.Td(id='x^x')]),
    ]),
])

# It is the callback operator, which will listen to the changes in "num-multi" input and updates five output elements.And they need to be in the same order as given in the input.
@callback(
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
    Output('x^x', 'children'),
    Input('num-multi', 'value'))
# THis is the callback function, this will recieve the input value from the user and return the output
def callback_a(x):   # x is taken to be the only input defined
    return x**2, x**3, 2**x, 3**x, x**x     # All these will go into the outputs as defined according to their order.

if __name__ == '__main__':
    app.run(port=5051)
Output
Alt Text


Explanation of the Above Code:

  1. First, we initialize a dashboard named app.

  2. Next, we define the app layout, which includes various input components. Each input component has attributes such as id, type, and value. The id='num-multi' allows Dash to track changes, and value=5 sets the initial value to 5.

  3. For the layout, we create a table using html.table. To define the rows of the table, we use html.Tr, and to specify the cells within those rows, we use html.Td.

  4. We then specify the callback decorator, which includes input and output components. The input component identifies the id and value, and it listens for changes in the input number. The output component indicates which table cell will be updated in response to these changes.

  5. Finally, we implement the callback function. This function is automatically triggered whenever the user inputs a new number, and it produces the corresponding output.

Hands on example of using dash

Dash is used to make interactive apps, so here we have created an interactive graph which shows the changes as we change the input from the dropdown.

import dash
from dash import dcc, html, Input, Output
import plotly.express as px
import pandas as pd
from sklearn.datasets import load_iris

# Load Iris dataset
iris = load_iris()
df = pd.DataFrame(data=iris.data, columns=iris.feature_names)
df['species'] = iris.target

# Create Dash app
app = dash.Dash(__name__)

# Layout
app.layout = html.Div([
    html.H1("Iris Dataset Visualization"),
    dcc.Dropdown(
        id='feature-dropdown',
        options=[
            {'label': feature, 'value': feature}
            for feature in iris.feature_names
        ],
        value=iris.feature_names[0]
    ),
    dcc.Graph(id='feature-graph')
])

# Callback to update graph
@app.callback(
    Output('feature-graph', 'figure'),
    [Input('feature-dropdown', 'value')]
)
def update_graph(selected_feature):
    fig = px.scatter(
        df,
        x=selected_feature,
        y='species',
        color='species',
        labels={'species': 'Species'},
        title=f'{selected_feature} vs. Species'
    )
    return fig

# Run app
if __name__ == '__main__':
    app.run_server(debug=True, port = 1007)
Output
Alt Text
Alt Text


This is a simple dash code that interactively displays a scatter plot of the selected feature against the species. The dropdown allows you to select different features from the Iris dataset, and the graph updates accordingly.

If you wish to make good and proper dash apps, you will have to use python IDES instead of jupyter or colab. In that case, upon saving and running the code, you will get a url like http://127.0.0.1:8050/ (8050 is the port, it is the default port but you can change it as discussed earlier) where your dash app will be running live.

Conclusion

What we have seen till now is just a glimpse of what you can do with dash from plotly. It has numerous more beautiful and engaging components. So don’t forget to keep referring to the official tutorial and continue learning more dash functions and objects.

Dash from Plotly changes how data scientists and analysts look at and understand data. It’s an easy-to-use, open-source tool that works well with popular data libraries, allowing users to build interactive web apps without much hassle. No matter if you’re an experienced programmer or just starting out, Dash offers clear instructions, community help, and user-friendliness, making it a great choice for turning data into interesting stories. As you start using Dash, you’ll find that the only limits to what you can visualize are your own creativity.

Practice

     To practice this wonderful library with a treasure of tools for data visualisation, before creating actual complex and useful apps, you can use https://wasmdash.vercel.app/ to create smaller and practice app with live output in the same window. It is extremely useful for trying out and learnign new things in Dash from Plotly. So do try it out…..Happy learning!!!